﻿using System;
using System.Collections.Generic;
using System.Web;

namespace TasksWebService
{
    public static class StorageHelper
    {
        private static string Path
        {
            get
            {
                return HttpContext.Current.Server.MapPath("~/") +
                    System.Configuration.ConfigurationManager.AppSettings["StoragePath"];
            }
        }

        private static string PathOf(Guid id)
        {
            return System.IO.Path.Combine(Path, id.ToString("D")) + ".xml";
        }

        public static string Get(Guid id)
        {
            string path = PathOf(id);
            if (System.IO.File.Exists(path))
                return System.IO.File.ReadAllText(path);
            return null;
        }

        public static string SaveAndMerge(string xml)
        {
            TasksModel.TaskSerializer<TasksModel.TaskLibrary> ts =
                new TasksModel.TaskSerializer<TasksModel.TaskLibrary>();
            TasksModel.TaskLibrary lib;
            try
            {
                lib = ts.Deserialize(xml);
            }
            catch (SystemException e)
            {
                throw new FormatException("Invalid xml", e);
            }
            string localXml = Get(lib.ID);
            if (localXml != null)
            {
                TasksModel.TaskLibrary local = ts.Deserialize(localXml);
                local.MergeWith(lib);
                xml = ts.Serialize(local);
            }

            string path = PathOf(lib.ID);
            System.IO.File.WriteAllText(path, xml);
            return xml;
        }

        public static List<string> GetLibraries()
        {
            TasksModel.TaskSerializer<TasksModel.TaskLibrary> ts =
                new TasksModel.TaskSerializer<TasksModel.TaskLibrary>();
            List<string> res = new List<string>();
            foreach (string file in System.IO.Directory.GetFiles(Path, "*.xml"))
            {
                string xml = System.IO.File.ReadAllText(file);
                TasksModel.TaskLibrary lib = ts.Deserialize(xml);
                res.Add(string.Format("{0}|{1}", lib.ID.ToString("D"), lib.CreatedBy != null ? lib.CreatedBy.Name : string.Empty));
            }
            return res;
        }
    }
}